package dao

import (
	"context"
	"time"

	"inventory/internal/model"
)

// FindLossOrderDetails 获取仓库下损耗单详情（只包含父记录）
func (d *Dao) FindLossOrderDetails(ctx context.Context, warehouseID, pageNo, pageSize int,
	startDate, endDate time.Time, keyWords string) (total int64, details []*model.LossDetail, err error) {
	db := d.TransContext(ctx).Model(&model.LossDetail{})
	db = db.Where(
		"create_time between ? and ? and warehouse_id = ? and parent_id = 0",
		startDate, endDate.Add(time.Hour*24-time.Second), warehouseID)
	if keyWords != "" {
		queryKeyWord := "%" + keyWords + "%"
		db = db.Where(
			"remark::jsonb->>'name' like ? or remark::jsonb->>'code' like ?",
			queryKeyWord, queryKeyWord)
	}
	if err = db.Count(&total).Error; err != nil {
		err = d.processSqlError(err)
		return
	}
	err = db.Order("id desc").Offset((pageNo - 1) * pageSize).Limit(pageSize).Find(&details).Error
	if err != nil {
		err = d.processSqlError(err)
	}
	return
}

// FindSubLossOrderDetails 获取子损耗单详情
func (d *Dao) FindSubLossOrderDetails(ctx context.Context, orderIDs []uint64) (details []*model.LossDetail, err error) {
	err = d.TransContext(ctx).Model(&model.LossDetail{}).Where(
		"order_id in ? and parent_id != 0", orderIDs).Find(&details).Error
	if err != nil {
		err = d.processSqlError(err)
	}
	return
}
